﻿using System;
using System.Threading.Tasks;
using UnityEngine;

namespace Framework
{
    public static class FrameworkExtension
    {
        public static T GetOrAddComponent<T>(this GameObject target) where T : MonoBehaviour
        {
            return target.TryGetComponent<T>(out var comp) ? comp : target.AddComponent<T>();
        }

        public static T GetOrAddComponent<T>(this Component target) where T : MonoBehaviour
        {
            return target.TryGetComponent<T>(out var comp) ? comp : target.gameObject.AddComponent<T>();
        }

        public static Task WaitForSeconds(this MonoBehaviour target, float seconds)
        {
#if UNITY_WEBGL && !UNITY_EDITOR
            return Task.Delay(TimeSpan.FromSeconds(seconds), target.destroyCancellationToken);
#else
            return Task.Delay(TimeSpan.FromSeconds(seconds), target.destroyCancellationToken).ContinueWith(_ => { }); // 微信平台执行ContinueWith后不会执行后续
#endif
        }
    }
}